﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;

public class PoolManager : MonoBehaviour {

    private static PoolManager _instance;//单例模式
    public static PoolManager _Instance { get { return _instance; } }

    public string ResourcesPath = "Prefabs";//要加载的对象存在的文件夹
     //字典用来存放所有的对象池 key为池子的名字 value 为单个池子
    public Dictionary<string, ObjectPool> PoolDic = new Dictionary<string, ObjectPool>();
    private void Awake()
    {
        _instance = this;
        LoadPools();
    }
    //注册一个对象池子
    public void Register(string name , int count)
    {
        string path = ResourcesPath + "/" + name;//得到对象保存的路径
        GameObject go = Resources.Load<GameObject>(path);//得到资源下的对象
        if (go == null)
        {
            return;
        }
        ObjectPool pool = new ObjectPool(go, name, count);//创建一个新的对象池
        PoolDic.Add(name, pool);//将新创建的对象池放在字典中
        Debug.Log("该池子注册成功，池子名字为:" + name + "，大小为：" + count);
    }
    //通过读取文件里面的加载信息来创建池子
    private void LoadPools()
    {
        string[] texts = File.ReadAllLines(PoolsText.Path);
        for (int i = 0; i < texts.Length; i++)
        {
            if (texts[i] == "")//如果为空数组
            {
                return;
            }
            string[] pool = texts[i].Split(',');
            string name = pool[0];
            int count = Convert.ToInt32(pool[1]);
            Register(name, count);
        }      
    }

   
    //获取对象
    public GameObject GetObject(string poolName)
    {
        if (!PoolDic.ContainsKey(poolName))
        {
            Debug.LogError(poolName + "是一个不存在的池子");
            return null;
        }
        else
        {         
            return PoolDic[poolName].GetObject();//取到相应池子里的对象
        }
    }
    //隐藏指定对象
    public void HideObject(GameObject go)
    {
        ObjectPool pool = null;
        foreach (ObjectPool p in PoolDic.Values)
        {
            if (p.PrefabList.Contains(go))
            {
                pool = p;
                break;
            }
        }
        if (pool != null)//如果找到了该对象
        {
            pool.HideObject(go);
        }
    }
    //隐藏某一个池子的所有物体
    public void HideAllObject(string poolName)
    {
        if (!PoolDic.ContainsKey(poolName))
        {
            Debug.LogError(poolName + "是一个不存在的池子");
            return;
        }
        else
        {
            //foreach (GameObject go in PoolDic[poolName].PrefabList)
            //{
            //    if (go.activeSelf)
            //    {
            //        go.SetActive(false);
            //    }
            //}
            ObjectPool pool = PoolDic[poolName];//得到相应的池子
            pool.HideAllObject();//隐藏池子全部对象
        }
    }
}
